package it.polimi.traveldream.web.beans.login;

import it.polimi.traveldream.managers.credentials.UserCredentialManager;
import it.polimi.traveldream.managers.credentials.UserCredentialManager.UserAlreadyExistsException;
import it.polimi.traveldream.persistence.dtos.UserDTO;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

@ManagedBean(name = "registerBean")
@RequestScoped
public class RegisterBean {

	@EJB
	private UserCredentialManager userMgr;

	private UserDTO user;

	public RegisterBean() {
		user = new UserDTO();
	}

	public UserDTO getUser() {
		return user;
	}

	public void setUser(UserDTO user) {
		this.user = user;
	}

	public String register() {
		System.out.println("Registering " + user.getEmail() + " : "
				+ user.getPassword());
		try {
			userMgr.save(user);
		} catch (UserAlreadyExistsException e) {
			String message = "The email is already in use by another user. Please change it.";
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(XHTMLPagesConstants.REGISTRATION_ERROR_MESSAGE,
					new FacesMessage(message));
			return "register?faces-redirect=true";
		}
		return "home?faces-redirect=true";
	}

	public void registerAdmin() {
		user.setIsClient(false);

		System.out.println("Registering " + user.getEmail() + " : "
				+ user.getPassword());
		try {
			userMgr.save(user);
		} catch (UserAlreadyExistsException e) {
			String message = "The email is already in use by another user. Please change it.";
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(XHTMLPagesConstants.REGISTRATION_ERROR_MESSAGE,
					new FacesMessage(message));

		}

	}

}
